package com.atguigu.utils;

import com.atguigu.constants.Constants;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;

/*
        工具类，存放静态方法
        1，创建命名空间
        2，判断表是否存在
        3，创建表（三张表，列族版本信息都不一样，可变参数）
     */
public class HBaseUtil {
    //创建命名空间
    public static void createNameSpace(String namespace) throws IOException {
        //1 获取connection对象
        Connection connection = ConnectionFactory.createConnection(Constants.CONFIGURATION);
        //2 获取Admin对象
        Admin admin = connection.getAdmin();
        //3 构建命名空间描述器
        NamespaceDescriptor build = NamespaceDescriptor.create(namespace).build();
        //4 创建命名空间
        admin.createNamespace(build);
        //5 关闭资源
        admin.close();
        connection.close();
    }
    //判断表是否存在
    public static boolean isTableExist(String tableName) throws IOException {
        //1 获取connection对象
        Connection connection = ConnectionFactory.createConnection(Constants.CONFIGURATION);
        //2 获取Admin对象
        Admin admin = connection.getAdmin();
        //3 判断是否存在
        boolean exists = admin.tableExists(TableName.valueOf(tableName));
        //4 关闭资源，返回值
        admin.close();
        connection.close();
        //5 返回值
        return exists;
    }
    //创建表
    public static void createTable(String tableName,int versions,String... columnsFamily) throws IOException {
        //1 判断是否传入了列族信息
        if (columnsFamily.length<=0){
            System.out.println("请设置列族信息！！！");
            return;
        }
        //2判断表是否存在
        if (isTableExist(tableName)){
            System.out.println(tableName+"表已经存在!!!");
        }
        //3 获取Connection对象
        Connection connection = ConnectionFactory.createConnection(Constants.CONFIGURATION);
        //4 获取Admin对象
        Admin admin = connection.getAdmin();
        //5 创建表描述器
        HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
        //6 循环添加列族信息
        for (String column:columnsFamily) {
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(column);
            //7 设置版本
            hColumnDescriptor.setMaxVersions(versions);
            hTableDescriptor.addFamily(hColumnDescriptor);
        }
        //8 创建表
        admin.createTable(hTableDescriptor);
        //9 关闭资源
        admin.close();
        connection.close();
    }

}
